(function(D){
    var images = [],
        pageIndice = 0,
        paper,
        image,
        zoom,
        updateImage,
        getZones,
        addPath,
        paths,
        deleteZone,
        zones,
        saveZone,
        nextPage,
        previousPage,
        linkIntervalZone,
        edId="transcription",
        annotator,
        pageId;

    linkIntervalZone = function(intervalId, zoneId){
        D.request("linkIntervalZone.txt", {
                interval: intervalId,
                zone: zoneId,
                user: D.userName,
                timestamp: D.timestamp()
            }, null, true);
    }

    nextPage = function(){
	    if(pageIndice != (images.length - 1)){
	        pageIndice += 1;
	        pageId = images[pageIndice].id;
	        updateImage();
            annotator.setId(pageId);
	    }
    }

    previousPage = function(){
	    if(pageIndice != 0){
	        pageIndice -= 1;
	        pageId = images[pageIndice].id;
	        updateImage();
            annotator.setId(pageId);
	    }
    }

    addPath = function(path, translatedPath){
	    var pathElem;

	    pathElem = paper.path(path).
	        scale(zoom,zoom,0,0).
	        animate({
	    	"stroke-width": 6,
	    	"stroke": "#aaa"
	        }, 1000, function(){
	    	    this.hide();
	        });
	    if(translatedPath) pathElem.strPath = translatedPath;
	    paths.push(pathElem);
	    return pathElem;
    }

    getZones = function(){
        D.request("getZones.txt",
		    {
		        "page": pageId
		    }, function(results){
		        var path;

		        $.each(results, function(i,r){
                    var set = $.grep(paths.items, function(item){ 
                                return (item.dbId && item.dbId === r.zoneId.value);
                              });
                    if(r.intervalId && set.length === 1){
                        set[0].intervals.push(D.makeHtmlId(r.intervalId.value));
                    }else{
                        path = addPath(r.path.value);
                        path.dbId = r.zoneId.value;
                        if(r.intervalId){
                            path.intervals = [D.makeHtmlId(r.intervalId.value)];
                        }else{
                            path.intervals = [];
                        }
                    }
		        });
		    });
    }

    updateImage = function(){
        var tempPoints = paper.set(),
            path = "",
            translatedPath = "";

        paths = paper.set();
        if(image) image.remove();
        image = paper.image(images[pageIndice].big, 0, 0, images[pageIndice].bigWidth, images[pageIndice].bigHeight);
        zoom = 0.4;
        image.scale(zoom,zoom,0,0);

        $(image.node).mousedown(function(e){
            var x0 = e.pageX,
                y0 = e.pageY,
                point,
                newPoint,
                strxy,
                pathElem;


            e.preventDefault();
            switch(e.which){
            case 1:
                $("body").mousemove(function(e){
                    var x1 = e.pageX,
                        y1 = e.pageY,
                        deltaX = x1-x0, deltaY = y1-y0;
                    
                    image.translate(deltaX,deltaY);
                    tempPoints.translate(deltaX,deltaY);
                    paths.translate(deltaX,deltaY);
                    x0 = x1;
                    y0 = y1;
                });
                $("body").mouseup(function(e){
                    $("body").unbind('mousemove');
                    $("body").unbind('mouseup');
                });
                break;
            case 3:
                newPoint = function(){
                    return paper.circle(e.pageX, e.pageY, 5).animate({"fill": "#fff"}, 1000);
                }

                strxy = function(translation){
                    var result, x, y;

                    if(!translation) translation = {x: 0, y: 0};
                    x = (point.attr("cx")-translation.x)*(1/zoom);
                    y = (point.attr("cy")-translation.y)*(1/zoom);
                    result = x + " " + y;
                    return result;
                }

                point = newPoint();
                tempPoints.push(point);
                if(tempPoints.length === 1){
                    path += "M " + strxy();
                    translatedPath += "M " + strxy(image.attr("translation"));
                    $(point.node).mousedown(function(){
                        path += " Z";
                        translatedPath += " Z";
                        pathElem = addPath(path, translatedPath);
                        pathElem.intervals = [];
                        path = "";
                        translatedPath = "";
                        tempPoints.remove();
                        tempPoints = paper.set();
                    });
                }else{
                    path += " L " + strxy();
                    translatedPath += " L " + strxy(image.attr("translation"));
                }
                break;
            }
        });
        getZones();
    }

    saveZone = function(strPath){
        var timestamp = D.timestamp(),
            zoneId = pageId + "/zones/" + timestamp;

        D.request("addZone.txt",
            {
                page: pageId,
                path: strPath,
                timestamp: timestamp,
                user: D.userName,
                zoneId: zoneId
            }, null, true);
        return zoneId;
    }

    deleteZone = function(zoneId){
        D.request("deleteZone1.txt",
            {
                zone: zoneId
            }, function(){
                D.request("deleteZone2.txt",
                    {
                        zone: zoneId,
                        user: D.userName,
                        timestamp: D.timestamp()
                    }, null, true);
            }, true);
    }

    zones = {
        zoneIndice:-1,
        zone: function() { return paths.items[zones.zoneIndice]; },
        current:false,
        fadeouts: [],
        addInterval: function(intervalId){
            if(zones.current){
                zones.zone().intervals.push(intervalId);
            }
        },
        next:function(){
            var zone; 

            zones.zoneIndice += 1;
            zone = zones.zone();

            $.each(zones.fadeouts, function(i,fadeout){
                fadeout();
            });
            zones.fadeouts = [];
            paths.hide();
            $("#deleteZone").hide();
            $("#saveZone").hide();
            if(zone){
                if(zone.removed){
                    zones.zoneIndice += 1;
                    zones.next();
                    return;
                }
                zones.current=zone;
                zone.show();
                $.each(zone.intervals, function(i,interval){
                    var e = D.textFrame(edId).find("#"+interval),
                        c;
                        
                    if(e.length){    
                        c = e.css("backgroundColor");
                        e.css('backgroundColor', '#aaaacc');
                        zones.fadeouts.push(function(){ 
                            e.css('backgroundColor', c);
                        })
                    }
                });
                $("#deleteZone").show();
                $("#deleteZone").unbind('click');
                if(zone.dbId){
                    $("#deleteZone").click(function(){
                        deleteZone(zone.dbId);
                        zone.remove();
                        $("#deleteZone").hide();
                    });
                }else{
                    $("#saveZone").show();
                    $("#saveZone").unbind('click');
                    $("#deleteZone").click(function(){
                        zone.remove();
                        $("#deleteZone").hide();
                        $("#saveZone").hide();
                    });
                    $("#saveZone").click(function(){
                        var zoneId = saveZone(zone.strPath);

                        zone.dbId = zoneId;
                        $("#saveZone").hide();
                    });
                }
            }else{
                zones.current=false;
                zones.zoneIndice = -1;
            }
        }
    };

    $(document).ready(function(){
        // L'identifiant de la page visualisée est passé en paramètre de l'URL
        pageId = location.href.split( "?" )[ 1 ].split( "&" )[ 0 ].split( "=" )[ 1 ];
        
        D.userName = self.opener.DESANTI.userName;

        images = self.opener.DESANTI.transcriptionLine.images;

        $.each(images, function(i,im){
            if(im.id === pageId){
                pageIndice = i;
                return false;
            }
        });

        paper = Raphael(0, 0, D.getDocWidth()/(1.6), D.getDocHeight());
        updateImage();

        $(document).bind("contextmenu", function(e){ return false; });

        $("#zoomPlus").button();
        $("#zoomMinus").button();
        $("#zoomPlus").click(function(){
            zoom += 0.05;
            image.scale(zoom,zoom,0,0);
            paths.scale(zoom,zoom,0,0);
        });
        $("#zoomMinus").click(function(){
            if(zoom > 0.1){
                zoom -= 0.05;
                image.scale(zoom,zoom,0,0);
                paths.scale(zoom,zoom,0,0);
            }
        });
        $("#previousPage").button();
        $("#previousPage").click(previousPage);
        $("#nextPage").button();
        $("#nextPage").click(nextPage);
        $("#zones").button();
        $("#zones").click(function(){zones.next();});
        $("#deleteZone").button().hide();
        $("#saveZone").button().hide();
        
        annotator = D.annotator(pageId, {
            edId: "transcription",
            save: "save",
            annotate: "annotate",
            terms: "terms"
            });
    });
})(DESANTI);
